/*
 * $Id: $
 */
package org.rcgwt.client.ui.grid.internal;

import java.util.Iterator;
import java.util.NoSuchElementException;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;

/**
 * 
 * @author Olivier Oeuillot (latest modification by $Author: $)
 * @version $Revision: $ $Date: $
 */
public class ChildrenElementIterable implements Iterable<Element>,
        Iterator<Element> {

    private Node cursor;

    protected ChildrenElementIterable(Element parent) {
        assert parent != null : "Null parent parameter !";

        this.cursor = parent.getFirstChild();
    }

    @Override
    public Iterator<Element> iterator() {
        return this;
    }

    @Override
    public boolean hasNext() {
        for (; cursor != null; cursor = cursor.getNextSibling()) {
            if (cursor.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            if (verifyType(cursor) == false) {
                continue;
            }

            return true;
        }

        return false;
    }

    protected boolean verifyType(Node node) {
        return true;
    }

    @Override
    public Element next() {
        if (hasNext() == false) {
            throw new NoSuchElementException();
        }

        Element node = Element.as(cursor);

        cursor = cursor.getNextSibling();

        return node;
    }

    @Override
    public void remove() {
        if (hasNext() == false) {
            throw new NoSuchElementException();
        }

        cursor.getParentNode().removeChild(cursor);
    }

    public static Iterable<Element> iterate(Element element) {
        return new ChildrenElementIterable(element);
    }
}
